<?php


namespace app\index\controller;
use think\cache\driver\Redis;
use think\Controller;

class Jqcmp extends Controller
{


    public function index(){
        $h = date('H');
        if($h==14){
            echo $h.'点---已经抓取<br>';
            $this->recheck();
        }else{
            echo '时间过啦<br>';
        }

        $time=1*60*60*1000; //刷新时间 3小时刷新一次页面
        echo ("<script>setTimeout('window.location.reload()',$time)</script>");
        echo ("--1小时自动刷新，14点抓取一次<br>");
        print_r('<h1 style="text-align: center;font-size: 80px;line-height: 2">'.date('Y-m-d H:i:s',time()).'</h1>');
        print_r('<h1 style="text-align: center;font-size: 80px;line-height: 2">err<br>不能关！！！</h1>');

    }


    public function test(){

        $uid = config('JQ_UID');
        $token = config('JQ_KEY');
        dump($uid);
        dump($token);
    }
    //关键词自动提交监控
    public function runtask()
    {

//        更新关键词 sid，ybyid
        $this->updatekey();
//        set_time_limit(100);
        //排名未查的
        $this->nopm();

        $w = [
//            'status' => ['in',[1,2,3,4,5]],
            'state' => 1,
//            'ybyid' => [['eq',0],['EXP','IS NULL'],'or']
           'ybyid' => 0
        ];

        //这里遍历你要查询的关键词
        $tasks = db('tb_webkey')->where($w)->field('id,name,url,sid,state')->limit(100)->select();

        foreach($tasks as $t){
            $key = trim($t['name']);
            $key = str_replace(" "," ",$key);//去全角空格
            $domain = trim($t['url']);
            $sid = $t['sid'];



            $res = jqcpm_add($sid,$key,$domain);
            $content = json_decode($res);

            if($content->code!=1){
                echo $t['id']." - $key - ".$content->msg." <br>";
            }
            $yid = $content->tid;

            $d = [];
            if(!$yid){
                $d['tstate'] = 0;
            }else{
                $d['ybyid'] = $yid; //更新apiID
                $d['tstate'] = 1; //加入api库状态
            }

            db('tb_webkey')->where(['id' => $t['id']])->update($d);
            echo $t['id']." - $key - $yid <br>";
        }


        return "执行完毕";
    }

    //任务监控消息通知  重点:这个地址请提供给我
    public function notice(){

        $redis=new \Redis();
        $redis->connect('127.0.0.1',6379);

        $tid = input('tid');
        $rank = input('rank');
        $update_time = input('update_time');

//排名小于20 更新
        if($rank<21 && $rank>0){
//                生成txt文件
            $data = [
                'tid' => $tid,
                'rank' => $rank,
                'update_time' => $update_time,
            ];
//            $data = json_encode($data);
//            $time = time();
//            $yunfile = ROOT_PATH . "/public_html/yunpm/jq-{$tid}-{$time}.txt";
//            file_put_contents($yunfile, $data);
//                生成txt文件

            $redis->lpush('wbKeyList',json_encode($data));
//            $count = db('tb_webkey')->where(['ybyid'=>$tid])->update(['nowPm'=>$rank,'pmtime'=>$update_time]);

        }
        $count = db('tb_webkey')->where(['ybyid'=>$tid])->count();
        if($count==0){
            jqcpm_del($tid);
        }
        return 1;
    }

//   api写入缓存
    public function notice_bak()
    {
        $tid = input('tid');
        $rank = input('rank');
        $update_time = input('update_time');
        $data = [
            'tid' => $tid,
            'rank' => $rank,
            'update_time' => $update_time,
        ];
        $data = json_encode($data);
        $time = time();
        $yunfile = ROOT_PATH . "/public_html/yunpm/jq-{$tid}-{$time}.txt";
        file_put_contents($yunfile, $data);
        return 1;
    }


    function recheck(){
        $uinfo = jqcpm_uinfo();
        $uinfo2 = json_decode($uinfo);

        $count = $uinfo2->count;
        $c1 = $uinfo2->c1;
        $c2 = $uinfo2->c2;

        $c = $c1+$c2;
        if($c>0){
            echo "总词数$count,待推送$c1,待查询$c2<br>";
            return "排名未处理完毕,请等待";
        }else{
            print_r('排名推送完毕，可以重新抓取');
//            $res=jqcpm_recheck();
//            print_r($res);
            $data = [];

            $uid = config('JQ_UID');
            $token = config('JQ_KEY');

            $data = [
                'uid' => $uid,
                'token' => $token,
                'gid' => 230,
            ];

            $url = "http://api.xseo.vip:8910/api/cpm/recheck";
            $res = request_post($url,$data);
            return $res;
        }

    }


    public function updatekey()
    {
        $rows=db('tb_webkey')
            ->where([
                'sid' => 0,
                'state'=>1 //正常词
            ])->select();

        foreach ($rows as $k => $v) {

            if ($v['sid'] == 0) {
                if ($v['typeid'] == 1) {
                    $sid = '1010';
                } elseif ($v['typeid'] == 2) {
                    $sid = '1015';
                } elseif ($v['typeid'] == 3) {
                    $sid = '7010';
                } elseif ($v['typeid'] == 4) {
                    $sid = '1030';
                } elseif ($v['typeid'] == 5) {
                    $sid = '7070';
                }
                db('tb_webkey')->where(['id' => $v['id']])->update(['sid' => $sid]);
            }

//            if($rows[$k]['typeid']==1){
////                $rows[$k]['sid'] =1010;
//                db('tb_webkey')->where(['typeid' => 1, 'id'=>$rows[$k]['id']])->update(['sid'=>1010]);
//            } elseif ($rows[$k]['typeid']==2){
////                $rows[$k]['sid'] =1015;
//                db('tb_webkey')->where(['typeid' => 2, 'id'=>$rows[$k]['id']])->update(['sid'=>1015]);
//
//            } elseif ($rows[$k]['typeid']==3){
////                $rows[$k]['sid'] =7010;
//                db('tb_webkey')->where(['typeid' => 3, 'id'=>$rows[$k]['id']])->update(['sid'=>7010]);
//
//            }elseif ($rows[$k]['typeid']==4){
////                $rows[$k]['sid'] =1030;
//                db('tb_webkey')->where(['typeid' => 4, 'id'=>$rows[$k]['id']])->update(['sid'=>1030]);
//            }elseif ($rows[$k]['typeid']==5){
////                $rows[$k]['sid'] =7070;
//                db('tb_webkey')->where(['typeid' => 5, 'id'=>$rows[$k]['id']])->update(['sid'=>7070]);
//            }

        }

        if($rows>0){
            return "关键词sid更新完毕";
        }else{
            return "关键词sid不需要更新";
        }

//        1:百度0
//        2:360
//        3:百度移动端
//        4:sogou
//        5:神马

//      1010://百度
//		1015://360
//		7010://百度移动
//		1030://搜狗
//		7070://神马
//		7015://360移动
//      7030://搜狗移动
//		7080: //头条

    }

    //排名未查的重查,这个请自动运行,有些词可能会推送失败,要自己手动获取一下
    public function nopm(){
        $h = date('H');
//        if($h<9){return "时间未到,9点后执行";}
        //判断是否查询完毕
        $uinfo = jqcpm_uinfo();
        $uinfo2 = json_decode($uinfo);
        $count = $uinfo2->count;
        $c1 = $uinfo2->c1;
        $c2 = $uinfo2->c2;

        $c = $c1+$c2;
        if($c>0){
            echo "总词数$count,待推送$c1,待查询$c2<br>";
            return "排名未处理完毕,请等待";
        }

        $today = date('Y-m-d');

        $w = [
            'state' => 1, #优化中的
            'ybyid' => ['gt', 0],
            'nowPm' => 0
        ];
        $c = db('tb_webkey')->where($w)->count();
        echo "<br>排名未查总条数:".$c."<br>";

        $res = db('tb_webkey')->where($w)->field('ybyid,nowPm')->limit(200)->select();
        foreach($res as $r){
            $d = jqcpm_info($r['ybyid']);
            $data = json_decode($d);
            if($data->code==1){
                if(!$data->data->xp){continue;}
                $ybyid = $data->data->id;
                $xp = $data->data->xp;
                $update_time = $data->data->update_time;

//               有排名才更新

                db('tb_webkey')->where(['ybyid'=>$ybyid])->update(['nowPm'=>$xp,'pmtime'=>$update_time]);
                    echo $ybyid."排名".$xp."已查询,已生成文件$update_time<br>";

//                if($xp>0 && $xp<$r['nowPm']){
//                    db('tb_webkey')->where(['ybyid'=>$ybyid])->update(['nowPm'=>$xp,'pmtime'=>$update_time]);
//                    echo $ybyid."排名".$xp."已查询,已生成文件$update_time<br>";
//                }else{
//                    echo $ybyid."排名".$xp.",旧排名".$r['nowPm']."未更新<br>";
//                }
            }else{
                db('tb_webkey')->where(['ybyid' => $r['ybyid']])->update([
                    'ybyid' => 0,
                    'tstate' => 0,
                ]); //api库中未查到
                echo "{$r['ybyid']}查询id不存再,已重置<br>";
            }

        }

        return "over";
    }


    //个别词单独查询再推送
    public function reNopm(){
        $today = date('Y-m-d');
        $w = [
            'state' => 1, #优化中的
//            'ybyid' => ['gt', 0],
            'ybyid' => ['in','5146483,1953950'],
            'nowPm' => 0,
//            'pmtime' => ['elt', $today]
        ];
        $c = db('tb_webkey')->where($w)->count();
//        echo db('tb_webkey')->getLastSql()."<br>";
        echo "<br>排名未查总条数:".$c."<br>";

        $res = db('tb_webkey')->where($w)->field('ybyid,nowPm')->limit(1)->select();
        foreach($res as $r){
            $d = jqcpm_info($r['ybyid']);
            $data = json_decode($d);
            if($data->code==1){
                if(!$data->data->xp){continue;}
                $ybyid = $data->data->id;
                $xp = $data->data->xp;
                $update_time = $data->data->update_time;

//               有排名才更新
                if($xp>0 && $xp<21){
                    db('tb_webkey')->where(['ybyid'=>$ybyid])->update(['nowPm'=>$xp,'pmtime'=>$update_time]);
                    echo $ybyid."排名".$xp."已查询,已生成文件$update_time<br>";
                }else{
                    db('tb_webkey')->where(['ybyid'=>$ybyid])->update(['pmtime'=>$update_time]);
                    echo $ybyid."排名".$xp.",旧排名".$r['nowPm']."未更新,$update_time<br>";
                }
            }else{
                db('tb_webkey')->where(['ybyid' => $r['ybyid']])->update([
                    'ybyid' => 0,
                    'tstate' => 0,
                ]); //api库中未查到
                echo "{$r['ybyid']}查询id不存再,已重置<br>";
            }

        }
//        echo ("<script>setTimeout('window.location.reload()',500);</script>");
        return "over";
    }


    //tb_webkey停词以后api库中删除 该词
    public function delapi(){
        $rows = db('tb_webkey')->where(['state'=>['<>',1], 'ybyid'=>['gt',0]])->field('id,name,state,tstate,ybyid,sid')->limit(100)->select();

        foreach($rows as $v){
            db('tb_webkey')->where(['id' => $v['id']])->update([
                'tstate'=>0,
                'ybyid'=>0
            ]);
            jqcpm_del($v['ybyid']);
            echo $v['id'].'更新成功<br>';
//
        }


        return "执行完毕";

    }
}